1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 import java.math.*;
32
33 public class NegateTests {
34
35 static BigDecimal negateThenRound(BigDecimal bd, MathContext mc) {
36 return bd.negate().plus(mc);
37 }
38
39
40 static BigDecimal absThenRound(BigDecimal bd, MathContext mc) {
41 return bd.abs().plus(mc);
42 }
43
44
45 static int negateTest(BigDecimal[][] testCases, MathContext mc) {
46 int failures = 0;
47
48 for (BigDecimal [] testCase : testCases) {
49
50 BigDecimal bd = testCase[0];
51 BigDecimal neg1 = bd.negate(mc);
52 BigDecimal neg2 = negateThenRound(bd, mc);
53 BigDecimal expected = testCase[1];
54
55 if (! neg1.equals(expected) ) {
56 failures++;
57 System.err.println("(" + bd + ").negate(" + mc + ") => " +
58 neg1 + " != expected " + expected);
59 }
60
61 if (! neg1.equals(neg2) ) {
62 failures++;
63 System.err.println("(" + bd + ").negate(" + mc + ") => " +
64 neg1 + " != ntr " + neg2);
65 }
66
67
68 BigDecimal abs = bd.abs(mc);
69 BigDecimal expectedAbs = absThenRound(bd,mc);
70 if (! abs.equals(expectedAbs) ) {
71 failures++;
72 System.err.println("(" + bd + ").abs(" + mc + ") => " +
73 abs + " != atr " + expectedAbs);
74 }
75
76 }
77
78 return failures;
79 }
80
81 static int negateTests() {
82 int failures = 0;
83 BigDecimal [][] testCasesCeiling = {
84 {new BigDecimal("1.3"), new BigDecimal("-1")},
85 {new BigDecimal("-1.3"), new BigDecimal("2")},
86 };
87
88 failures += negateTest(testCasesCeiling,
89 new MathContext(1, RoundingMode.CEILING));
90
91 BigDecimal [][] testCasesFloor = {
92 {new BigDecimal("1.3"), new BigDecimal("-2")},
93 {new BigDecimal("-1.3"), new BigDecimal("1")},
94 };
95
96 failures += negateTest(testCasesFloor,
97 new MathContext(1, RoundingMode.FLOOR));
98
99 return failures;
100 }
101
102 public static void main(String argv[]) {
103 int failures = 0;
104
105 failures += negateTests();
106
107 if (failures > 0 )
108 throw new RuntimeException("Incurred " + failures + " failures" +
109 " testing the negate and/or abs.");
110 }
111 }